<template>
  <ElFormItem
    :prop="data.id"
    :class="{ 'is-active': data.id === (viewer && viewer.activeWidgetId) }"
    :widget-id="data.id"
    :rules="rules"
    size="mini"
  >
    <span class="fa-widget-fill-item__label" slot="label" :title="data.labelUsing">{{ data.labelUsing }}</span>
    <slot v-bind="{ data }">
      <Components
        :is="data.option.fillingComponent"
        :data="data"
        :readonly="readonly"
        :viewer="viewer"
        @click.native="onFieldClick"
      />
    </slot>
  </ElFormItem>
</template>

<script lang="ts">
import { defineComponent, PropType, computed, inject } from 'vue'
import { Widget } from '@/models'
import { Viewer } from '@/types'
import { EffectLock } from '@/utils'

export default defineComponent({
  name: 'WidgetFillItem',

  props: {
    /** 控件数据 */
    data: {
      type: Widget,
      required: true
    },

    /** 文档查看组件 */
    viewer: Object as PropType<Viewer>
  },

  setup(props) {
    /** 控件填写组件 */
    const WidgetFill = inject('WidgetFill') as Vue

    /** 点击锁定，避免重复触发锁定 */
    const clickLocker = new EffectLock(50)

    return {
      /** 指定数据来源时只读 */
      readonly: computed(() => !!props.data.sourceItem),

      /** 校验规则 */
      rules: computed(() => [
        {
          required: props.data.required,

          validator(rule: object, value: string | number, callback: (e?: Error) => void) {
            const { errorUsing: error } = props.data
            if (error) {
              return callback(new Error(error))
            }

            callback()
          },

          trigger: 'blur'
        }
      ]),

      /** 点击 */
      onFieldClick(e: MouseEvent) {
        if (clickLocker.locked) return

        clickLocker.lock()

        WidgetFill.$emit('field-click', props.data, e)
      }
    }
  }
})
</script>

<style lang="scss">
.fa-widget-fill.el-form .el-form-item {
  margin-bottom: 0;
  padding: 0 16px 20px;
  transition: background-color 0.2s ease-in-out;

  &.is-active {
    background-color: $color-primary-lightest;
  }

  &__label {
    width: 100%;
    padding: 0;
  }
}

.fa-widget-fill-item__label {
  display: inline-block;
  max-width: 100%;
  vertical-align: middle;
  @include text-ellipsis;
}
</style>
